<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="okhttp,">










<meta name="description" content="版权声明：本文为博主原创文章，未经博主允许不得转载。如果觉得文章不错，记得顶一下！GitHub: https://github.com/iSpring https://blog.csdn.net/sunqunsunqun/article/details/51661195在Android开发中，发送HTTP请求是很常见的。SDK中自带的HttpURLConnection虽然能基本满足需求，但是在使用">
<meta name="keywords" content="okhttp">
<meta property="og:type" content="article">
<meta property="og:title" content="Okhttp使用详解">
<meta property="og:url" content="https://blog.xiezc.xyz/2018/11/07/OKHTTP的使用教程/index.html">
<meta property="og:site_name" content="xiezc的小站">
<meta property="og:description" content="版权声明：本文为博主原创文章，未经博主允许不得转载。如果觉得文章不错，记得顶一下！GitHub: https://github.com/iSpring https://blog.csdn.net/sunqunsunqun/article/details/51661195在Android开发中，发送HTTP请求是很常见的。SDK中自带的HttpURLConnection虽然能基本满足需求，但是在使用">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-04-04T14:39:48.642Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Okhttp使用详解">
<meta name="twitter:description" content="版权声明：本文为博主原创文章，未经博主允许不得转载。如果觉得文章不错，记得顶一下！GitHub: https://github.com/iSpring https://blog.csdn.net/sunqunsunqun/article/details/51661195在Android开发中，发送HTTP请求是很常见的。SDK中自带的HttpURLConnection虽然能基本满足需求，但是在使用">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.xiezc.xyz/2018/11/07/OKHTTP的使用教程/">





  <title>Okhttp使用详解 | xiezc的小站</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8ae02d8cf311eabbae2621ff2d51a260";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xiezc的小站</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">xiezc的小站</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.xiezc.xyz/2018/11/07/OKHTTP的使用教程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xiezc">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xiezc的小站">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Okhttp使用详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-07T13:23:58+08:00">
                2018-11-07
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/11/07/OKHTTP的使用教程/" class="leancloud_visitors" data-flag-title="Okhttp使用详解">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>版权声明：本文为博主原创文章，未经博主允许不得转载。如果觉得文章不错，记得顶一下！GitHub: <a href="https://github.com/iSpring" target="_blank" rel="noopener">https://github.com/iSpring</a> <a href="https://blog.csdn.net/sunqunsunqun/article/details/51661195" target="_blank" rel="noopener">https://blog.csdn.net/sunqunsunqun/article/details/51661195</a><br>在Android开发中，发送HTTP请求是很常见的。SDK中自带的HttpURLConnection虽然能基本满足需求，但是在使用上有诸多不便，为此，square公司实现了一个HTTP客户端的类库——Okhttp 。</p>
<p>Okhttp是一个支持HTTP 和 HTTP/2 的客户端，可以在Android和Java应用程序中使用，其具有以下特点： </p>
<ol>
<li>API设计轻巧，基本上通过几行代码的链式调用即可获取结果。 </li>
<li>既支持同步请求，也支持异步请求。同步请求会阻塞当前线程，异步请求不会阻塞当前线程，异步执行完成后执行相应的回调方法。 </li>
<li>其支持HTTP/2协议，通过HTTP/2，可以让客户端中到同一服务器的所有请求共用同一个Socket连接。 </li>
<li>如果请求不支持HTTP/2协议，那么Okhttp会在内部维护一个连接池， 通过该连接池，可以对HTTP/1.x的连接进行重用，减少了延迟。 </li>
<li>透明的GZIP处理降低了下载数据的大小。 </li>
<li>请求的数据会进行相应的缓存处理，下次再进行请求时，如果服务器告知304（表明数据没有发生变化），那么就直接从缓存中读取数据，降低了重复请求的数量。</li>
</ol>
<p>当前Okhttp最新的版本是3.x，支持Android 2.3+。要想在Java应用程序中使用Okhttp，JRE的最低版本要求是1.7。</p>
<p>Okhttp API： <a href="http://square.github.io/okhttp/3.x/okhttp/" target="_blank" rel="noopener">http://square.github.io/okhttp/3.x/okhttp/</a></p>
<p>本文中的代码来自于Okhttp的官方Wiki中的示例代码。</p>
<h2 id="下载Okhttp"><a href="#下载Okhttp" class="headerlink" title="下载Okhttp"></a>下载Okhttp</h2><p>可以点此下载最新的Okhttp的jar包，也可以通过Maven获取：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.squareup.okhttp3<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>okhttp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.3.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>也可以在Gradle中进行如下配置以便在Android Studio中使用：</p>
<figure class="highlight plain"><figcaption><span>'com.squareup.okhttp3:okhttp:3.3.1'```</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">## 核心类</span><br><span class="line"></span><br><span class="line">我们在使用Okhttp进行开发的时候，主要牵扯到以下几个核心类：`OkHttpClient`、`Request`、`Call` 和 `Response`。</span><br><span class="line"></span><br><span class="line">### OkHttpClient </span><br><span class="line"></span><br><span class="line">OkHttpClient表示了HTTP请求的客户端类，在绝大多数的App中，我们只应该执行一次new OkHttpClient()，将其作为全局的实例进行保存，从而在App的各处都只使用这一个实例对象，这样所有的HTTP请求都可以共用Response缓存、共用线程池以及共用连接池。</span><br><span class="line"></span><br><span class="line">默认情况下，直接执行OkHttpClient client = new OkHttpClient()就可以实例化一个OkHttpClient对象。</span><br><span class="line"></span><br><span class="line">可以配置OkHttpClient的一些参数，比如超时时间、缓存目录、代理、Authenticator等，那么就需要用到内部类OkHttpClient.Builder，设置如下所示：</span><br><span class="line"></span><br><span class="line">```java</span><br><span class="line">OkHttpClient client = new OkHttpClient.Builder().</span><br><span class="line">        readTimeout(30, TimeUnit.SECONDS).</span><br><span class="line">        cache(cache).</span><br><span class="line">        proxy(proxy).</span><br><span class="line">        authenticator(authenticator).</span><br><span class="line">        build();</span><br></pre></td></tr></table></figure>
<p>OkHttpClient本身不能设置参数，需要借助于其内部类Builder设置参数，参数设置完成后，调用Builder的build方法得到一个配置好参数的OkHttpClient对象。这些配置的参数会对该OkHttpClient对象所生成的所有HTTP请求都有影响。</p>
<p>有时候我们想单独给某个网络请求设置特别的几个参数，比如只想让某个请求的超时时间设置为一分钟，但是还想保持OkHttpClient对象中的其他的参数设置，那么可以调用OkHttpClient对象的newBuilder()方法，代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">OkHttpClient client = ...</span><br><span class="line">    </span><br><span class="line">OkHttpClient clientWith60sTimeout = client.newBuilder().</span><br><span class="line">        readTimeout(<span class="number">60</span>, TimeUnit.SECONDS).</span><br><span class="line">        build();</span><br></pre></td></tr></table></figure>
<p>clientWith60sTimeout中的参数来自于client中的配置参数，只不过它覆盖了读取超时时间这一个参数，其余参数与client中的一致。</p>
<h3 id="Request"><a href="#Request" class="headerlink" title="Request"></a>Request</h3><p>Request类封装了请求报文信息：请求的Url地址、请求的方法（如GET、POST等）、各种请求头（如Content-Type、Cookie）以及可选的请求体。一般通过内部类Request.Builder的链式调用生成Request对象。</p>
<p>Call<br>Call代表了一个实际的HTTP请求，它是连接Request和Response的桥梁，通过Request对象的newCall()方法可以得到一个Call对象。Call对象既支持同步获取数据，也可以异步获取数据。</p>
<p>执行Call对象的execute()方法，会阻塞当前线程去获取数据，该方法返回一个Response对象。<br>执行Call对象的enqueue()方法，不会阻塞当前线程，该方法接收一个Callback对象，当异步获取到数据之后，会回调执行Callback对象的相应方法。如果请求成功，则执行Callback对象的onResponse方法，并将Response对象传入该方法中；如果请求失败，则执行Callback对象的onFailure方法。<br>Response<br>Response类封装了响应报文信息：状态吗（200、404等）、响应头（Content-Type、Server等）以及可选的响应体。可以通过Call对象的execute()方法获得Response对象，异步回调执行Callback对象的onResponse方法时也可以获取Response对象。</p>
<p>同步GET<br>以下示例演示了如何同步发送GET请求，输出响应头以及将响应体转换为字符串。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> OkHttpClient client = <span class="keyword">new</span> OkHttpClient();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">  Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">      .url(<span class="string">"http://publicobject.com/helloworld.txt"</span>)</span><br><span class="line">      .build();</span><br><span class="line">  Response response = client.newCall(request).execute();</span><br><span class="line">  <span class="keyword">if</span> (!response.isSuccessful()) <span class="keyword">throw</span> <span class="keyword">new</span> IOException(<span class="string">"Unexpected code "</span> + response);</span><br><span class="line">  Headers responseHeaders = response.headers();</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; responseHeaders.size(); i++) &#123;</span><br><span class="line">    System.out.println(responseHeaders.name(i) + <span class="string">": "</span> + responseHeaders.value(i));</span><br><span class="line">  &#125;</span><br><span class="line">  System.out.println(response.body().string());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面对以上代码进行简单说明：</p>
<p>client执行newCall方法会得到一个Call对象，表示一个新的网络请求。</p>
<p>Call对象的execute方法是同步方法，会阻塞当前线程，其返回Response对象。</p>
<p>通过Response对象的isSuccessful()方法可以判断请求是否成功。</p>
<p>通过Response的headers()方法可以得到响应头Headers对象，可以通过for循环索引遍历所有的响应头的名称和值。可以通过Headers.name(index)方法获取响应头的名称，通过Headers.value(index)方法获取响应头的值。</p>
<p>除了索引遍历，通过Headers.get(headerName)方法也可以获取某个响应头的值，比如通过headers.get(“Content-Type”)获得服务器返回给客户端的数据类型。但是服务器返回给客户端的响应头中有可能有多个重复名称的响应头，比如在某个请求中，服务器要向客户端设置多个Cookie，那么会写入多个Set-Cookie响应头，且这些Set-Cookie响应头的值是不同的，访问百度首页，可以看到有7个Set-Cookie的响应头，如下图所示：</p>
<p>为了解决同时获取多个name相同的响应头的值，Headers中提供了一个public List<string> values(String name)方法，该方法会返回一个List<string>对象，所以此处通过Headers对象的values(‘Set-Cookie’)可以获取全部的Cookie信息，如果调用Headers对象的get(‘Set-Cookie’)方法，那么只会获取最后一条Cookie信息。</string></string></p>
<p>通过Response对象的body()方法可以得到响应体ResponseBody对象，调用其string()方法可以很方便地将响应体中的数据转换为字符串，该方法会将所有的数据放入到内存之中，所以如果数据超过1M，最好不要调用string()方法以避免占用过多内存，这种情况下可以考虑将数据当做Stream流处理。</p>
<p>异步GET<br>以下示例演示了如何异步发送GET网络请求，代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> OkHttpClient client = <span class="keyword">new</span> OkHttpClient();</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    Request request = <span class="keyword">new</span> Request.Builder()</span><br><span class="line">        .url(<span class="string">"http://publicobject.com/helloworld.txt"</span>)</span><br><span class="line">        .build();</span><br><span class="line"></span><br><span class="line">    client.newCall(request).enqueue(<span class="keyword">new</span> Callback() &#123;</span><br><span class="line">          <span class="meta">@Override</span></span><br><span class="line">          <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call call, IOException e)</span> </span>&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">          &#125;</span><br><span class="line"></span><br><span class="line">          <span class="meta">@Override</span></span><br><span class="line">          <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call call, Response response)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (!response.isSuccessful()) <span class="keyword">throw</span> <span class="keyword">new</span> IOException(<span class="string">"Unexpected code "</span> + response);</span><br><span class="line">            Headers responseHeaders = response.headers();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>, size = responseHeaders.size(); i &lt; size; i++) &#123;</span><br><span class="line">              System.out.println(responseHeaders.name(i) + <span class="string">": "</span> + responseHeaders.value(i));</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(response.body().string());</span><br><span class="line">          &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>下面对以上代码进行一下说明：</p>
<p>要想异步执行网络请求，需要执行Call对象的enqueue方法，该方法接收一个okhttp3.Callback对象，enqueue方法不会阻塞当前线程，会新开一个工作线程，让实际的网络请求在工作线程中执行。一般情况下这个工作线程的名字以“Okhttp”开头，并包含连接的host信息，比如上面例子中的工作线程的name是”Okhttp <a href="http://publicobject.com/...&quot;" target="_blank" rel="noopener">http://publicobject.com/...&quot;</a></p>
<p>当异步请求成功后，会回调Callback对象的onResponse方法，在该方法中可以获取Response对象。当异步请求失败或者调用了Call对象的cancel方法时，会回调Callback对象的onFailure方法。onResponse和onFailure这两个方法都是在工作线程中执行的。</p>
<p>请求头和响应头<br>典型的HTTP请求头、响应头都是类似于Map&lt;String, String&gt;，每个name对应一个value值。不过像我们之前提到的，也会存在多个name重复的情况，比如相应结果中就有可能存在多个Set-Cookie响应头，同样的，也可能同时存在多个名称一样的请求头。响应头的读取我们在上文已经说过了，在此不再赘述。一般情况下，我们只需要调用header(name, value)方法就可以设置请求头的name和value，调用该方法会确保整个请求头中不会存在多个名称一样的name。如果想添加多个name相同的请求头，应该调用addHeader(name, value)方法，这样可以添加重复name的请求头，其value可以不同，例如如下所示：</p>
<p>  private final OkHttpClient client = new OkHttpClient();</p>
<p>  public void run() throws Exception {<br>    Request request = new Request.Builder()<br>        .url(“<a href="https://api.github.com/repos/square/okhttp/issues&quot;" target="_blank" rel="noopener">https://api.github.com/repos/square/okhttp/issues&quot;</a>)<br>        .header(“User-Agent”, “OkHttp Headers.java”)<br>        .addHeader(“Accept”, “application/json; q=0.5”)<br>        .addHeader(“Accept”, “application/vnd.github.v3+json”)<br>        .build();</p>
<pre><code>Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response);

System.out.println(&quot;Server: &quot; + response.header(&quot;Server&quot;));
System.out.println(&quot;Date: &quot; + response.header(&quot;Date&quot;));
System.out.println(&quot;Vary: &quot; + response.headers(&quot;Vary&quot;));
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>上面的代码通过addHeader方法添加了两个Accept请求头，且二者的值不同，这样服务器收到客户端发来的请求后，就知道客户端既支持application/json类型的数据，也支持application/vnd.github.v3+json类型的数据。</p>
<p>用POST发送String<br>可以使用POST方法发送请求体。下面的示例演示了如何将markdown文本作为请求体发送到服务器，服务器会将其转换成html文档，并发送给客户端。</p>
<p>  public static final MediaType MEDIA_TYPE_MARKDOWN<br>      = MediaType.parse(“text/x-markdown; charset=utf-8”);</p>
<p>  private final OkHttpClient client = new OkHttpClient();</p>
<p>  public void run() throws Exception {<br>    String postBody = “”</p>
<pre><code>    + &quot;Releases\n&quot;
    + &quot;--------\n&quot;
    + &quot;\n&quot;
    + &quot; * _1.0_ May 6, 2013\n&quot;
    + &quot; * _1.1_ June 15, 2013\n&quot;
    + &quot; * _1.2_ August 11, 2013\n&quot;;

Request request = new Request.Builder()
    .url(&quot;https://api.github.com/markdown/raw&quot;)
    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response);

System.out.println(response.body().string());
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>下面对以上代码进行说明：</p>
<p>Request.Builder的post方法接收一个RequestBody对象。</p>
<p>RequestBody就是请求体，一般可通过调用该类的5个重载的static的create()方法得到RequestBody对象。create()方法第一个参数都是MediaType类型，create()方法的第二个参数可以是String、File、byte[]或okio.ByteString。除了调用create()方法，还可以调用RequestBody的writeTo()方法向其写入数据，writeTo()方法一般在用POST发送Stream流的时候使用。</p>
<p>MediaType指的是要传递的数据的MIME类型，MediaType对象包含了三种信息：type、subtype以及CharSet，一般将这些信息传入parse()方法中，这样就能解析出MediaType对象，比如在上例中text/x-markdown; charset=utf-8，type值是text，表示是文本这一大类；/后面的x-markdown是subtype，表示是文本这一大类下的markdown这一小类；charset=utf-8则表示采用UTF-8编码。如果不知道某种类型数据的MIME类型，可以参见连接Media Types和MIME 参考手册，较详细地列出了所有的数据的MIME类型。以下是几种常见数据的MIME类型值：</p>
<p>json ：application/json<br>xml：application/xml<br>png：image/png<br>jpg： image/jpeg<br>gif：image/gif<br>在该例中，请求体会放置在内存中，所以应该避免用该API发送超过1M的数据。</p>
<p>用POST发送Stream流<br>下面的示例演示了如何使用POST发送Stream流。</p>
<p>  public static final MediaType MEDIA_TYPE_MARKDOWN<br>      = MediaType.parse(“text/x-markdown; charset=utf-8”);</p>
<p>  private final OkHttpClient client = new OkHttpClient();</p>
<p>  public void run() throws Exception {<br>    RequestBody requestBody = new RequestBody() {<br>      @Override public MediaType contentType() {<br>        return MEDIA_TYPE_MARKDOWN;<br>      }</p>
<pre><code>  @Override public void writeTo(BufferedSink sink) throws IOException {
    sink.writeUtf8(&quot;Numbers\n&quot;);
    sink.writeUtf8(&quot;-------\n&quot;);
    for (int i = 2; i &lt;= 997; i++) {
      sink.writeUtf8(String.format(&quot; * %s = %s\n&quot;, i, factor(i)));
    }
  }

  private String factor(int n) {
    for (int i = 2; i &lt; n; i++) {
      int x = n / i;
      if (x * i == n) return factor(x) + &quot; × &quot; + i;
    }
    return Integer.toString(n);
  }
};

Request request = new Request.Builder()
    .url(&quot;https://api.github.com/markdown/raw&quot;)
    .post(requestBody)
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response);

System.out.println(response.body().string());
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>31<br>32<br>33<br>34<br>35<br>36<br>37<br>38<br>下面对以上代码进行说明：</p>
<p>以上代码在实例化RequestBody对象的时候重写了contentType()和writeTo()方法。</p>
<p>覆写contentType()方法，返回markdown类型的MediaType。</p>
<p>覆写writeTo()方法，该方法会传入一个Okia的BufferedSink类型的对象，可以通过BufferedSink的各种write方法向其写入各种类型的数据，此例中用其writeUtf8方法向其中写入UTF-8的文本数据。也可以通过它的outputStream()方法，得到输出流OutputStream，从而通过OutputSteram向BufferedSink写入数据。</p>
<p>用POST发送File<br>下面的代码演示了如何用POST发送文件。</p>
<p>  public static final MediaType MEDIA_TYPE_MARKDOWN<br>      = MediaType.parse(“text/x-markdown; charset=utf-8”);</p>
<p>  private final OkHttpClient client = new OkHttpClient();</p>
<p>  public void run() throws Exception {<br>    File file = new File(“README.md”);</p>
<pre><code>Request request = new Request.Builder()
    .url(&quot;https://api.github.com/markdown/raw&quot;)
    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response);

System.out.println(response.body().string());
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>我们之前提到，RequestBody.create()静态方法可以接收File参数，将File转换成请求体，将其传递给post()方法。</p>
<p>用POST发送Form表单中的键值对<br>如果想用POST发送键值对字符串，可以使用在post()方法中传入FormBody对象，FormBody继承自RequestBody，类似于Web前端中的Form表单。可以通过FormBody.Builder构建FormBody。</p>
<p>示例代码如下所示：</p>
<p>  private final OkHttpClient client = new OkHttpClient();</p>
<p>  public void run() throws Exception {<br>    RequestBody formBody = new FormBody.Builder()<br>        .add(“search”, “Jurassic Park”)<br>        .build();<br>    Request request = new Request.Builder()<br>        .url(“<a href="https://en.wikipedia.org/w/index.php&quot;" target="_blank" rel="noopener">https://en.wikipedia.org/w/index.php&quot;</a>)<br>        .post(formBody)<br>        .build();</p>
<pre><code>Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response);

System.out.println(response.body().string());
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>需要注意的是，在发送数据之前，Android会对非ASCII码字符调用encodeURIComponent方法进行编码，例如”Jurassic Park”会编码成”Jurassic%20Park”，其中的空格符被编码成%20了，服务器端会其自动解码。</p>
<p>用POST发送multipart数据<br>我们可以通过Web前端的Form表单上传一个或多个文件，Okhttp也提供了对应的功能，如果我们想同时发送多个Form表单形式的文件，就可以使用在post()方法中传入MultipartBody对象。MultipartBody继承自RequestBody，也表示请求体。只不过MultipartBody的内部是由多个part组成的，每个part就单独包含了一个RequestBody请求体，所以可以把MultipartBody看成是一个RequestBody的数组，而且可以分别给每个RequestBody单独设置请求头。</p>
<p>示例代码如下所示：</p>
<p>  private static final String IMGUR_CLIENT_ID = “…”;<br>  private static final MediaType MEDIA_TYPE_PNG = MediaType.parse(“image/png”);</p>
<p>  private final OkHttpClient client = new OkHttpClient();</p>
<p>  public void run() throws Exception {<br>    // Use the imgur image upload API as documented at <a href="https://api.imgur.com/endpoints/image" target="_blank" rel="noopener">https://api.imgur.com/endpoints/image</a><br>    RequestBody requestBody = new MultipartBody.Builder()<br>        .setType(MultipartBody.FORM)<br>        .addFormDataPart(“title”, “Square Logo”)<br>        .addFormDataPart(“image”, “logo-square.png”,<br>            RequestBody.create(MEDIA_TYPE_PNG, new File(“website/static/logo-square.png”)))<br>        .build();</p>
<pre><code>Request request = new Request.Builder()
    .header(&quot;Authorization&quot;, &quot;Client-ID &quot; + IMGUR_CLIENT_ID)
    .url(&quot;https://api.imgur.com/3/image&quot;)
    .post(requestBody)
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response);

System.out.println(response.body().string());
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>下面对以上代码进行说明：</p>
<p>MultipartBody要通过其内部类MultipartBody.Builder进行构建。</p>
<p>通过MultipartBody.Builder的setType()方法设置MultipartBody的MediaType类型，一般情况下，将该值设置为MultipartBody.FORM，即W3C定义的multipart/form-data类型，详见Forms in HTML documents。</p>
<p>通过MultipartBody.Builder的方法addFormDataPart(String name, String value)或addFormDataPart(String name, String filename, RequestBody body)添加数据，其中前者添加的是字符串键值对数据，后者可以添加文件。</p>
<p>MultipartBody.Builder还提供了三个重载的addPart方法，其中通过addPart(Headers headers, RequestBody body)方法可以在添加RequestBody的时候，同时为其单独设置请求头。</p>
<p>用Gson处理JSON响应<br>Gson是Google开源的一个用于进行JSON处理的Java库，通过Gson可以很方面地在JSON和Java对象之间进行转换。我们可以将Okhttp和Gson一起使用，用Gson解析返回的JSON结果。</p>
<p>下面的示例代码演示了如何使用Gson解析GitHub API的返回结果。</p>
<p>  private final OkHttpClient client = new OkHttpClient();<br>  private final Gson gson = new Gson();</p>
<p>  public void run() throws Exception {<br>    Request request = new Request.Builder()<br>        .url(“<a href="https://api.github.com/gists/c2a7c39532239ff261be&quot;" target="_blank" rel="noopener">https://api.github.com/gists/c2a7c39532239ff261be&quot;</a>)<br>        .build();<br>    Response response = client.newCall(request).execute();<br>    if (!response.isSuccessful()) throw new IOException(“Unexpected code “ + response);</p>
<pre><code>Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
for (Map.Entry&lt;String, GistFile&gt; entry : gist.files.entrySet()) {
  System.out.println(entry.getKey());
  System.out.println(entry.getValue().content);
}
</code></pre><p>  }</p>
<p>  static class Gist {<br>    Map&lt;String, GistFile&gt; files;<br>  }</p>
<p>  static class GistFile {<br>    String content;<br>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>下面对以上代码进行说明：</p>
<p>访问GitHub的<a href="https://api.github.com/gists/c2a7c39532239ff261be的返回结果如下所示：" target="_blank" rel="noopener">https://api.github.com/gists/c2a7c39532239ff261be的返回结果如下所示：</a> </p>
<p>Gist类对应着整个JSON的返回结果，Gist中的Map&lt;String, GistFile&gt; files对应着JSON中的files。</p>
<p>files中的每一个元素都是一个key-value的键值对，key是String类型，value是GistFile类型，并且GistFile中必须包含一个String content。OkHttp.txt就对应着一个GistFile对象，其content值就是GistFile中的content。</p>
<p>通过代码Gist gist = gson.fromJson(response.body().charStream(), Gist.class)，将JSON字符串转换成了Java对象。将ResponseBody的charStream方法返回的Reader传给Gson的fromJson方法，然后传入要转换的Java类的class。</p>
<p>缓存响应结果<br>如果想缓存响应结果，我们就需要为Okhttp配置缓存目录，Okhttp可以写入和读取该缓存目录，并且我们需要限制该缓存目录的大小。Okhttp的缓存目录应该是私有的，不能被其他应用访问。</p>
<p>Okhttp中，多个缓存实例同时访问同一个缓存目录会出错，大部分的应用只应该调用一次new OkHttpClient()，然后为其配置缓存目录，然后在App的各个地方都使用这一个OkHttpClient实例对象，否则两个缓存实例会互相影响，导致App崩溃。</p>
<p>缓存示例代码如下所示：</p>
<p>  private final OkHttpClient client;</p>
<p>  public CacheResponse(File cacheDirectory) throws Exception {<br>    int cacheSize = 10 <em> 1024 </em> 1024; // 10 MiB<br>    String okhttpCachePath = getCacheDir().getPath() + File.separator + “okhttp”;<br>    File okhttpCache = new File(okhttpCachePath);<br>    if(!okhttpCache.exists()){<br>        okhttpCache.mkdirs();<br>    }</p>
<pre><code>Cache cache = new Cache(okhttpCache, cacheSize);

client = new OkHttpClient.Builder()
    .cache(cache)
    .build();
</code></pre><p>  }</p>
<p>  public void run() throws Exception {<br>    Request request = new Request.Builder()<br>        .url(“<a href="http://publicobject.com/helloworld.txt&quot;" target="_blank" rel="noopener">http://publicobject.com/helloworld.txt&quot;</a>)<br>        .build();</p>
<pre><code>Response response1 = client.newCall(request).execute();
if (!response1.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response1);

String response1Body = response1.body().string();
System.out.println(&quot;Response 1 response:          &quot; + response1);
System.out.println(&quot;Response 1 cache response:    &quot; + response1.cacheResponse());
System.out.println(&quot;Response 1 network response:  &quot; + response1.networkResponse());

Response response2 = client.newCall(request).execute();
if (!response2.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response2);

String response2Body = response2.body().string();
System.out.println(&quot;Response 2 response:          &quot; + response2);
System.out.println(&quot;Response 2 cache response:    &quot; + response2.cacheResponse());
System.out.println(&quot;Response 2 network response:  &quot; + response2.networkResponse());

System.out.println(&quot;Response 2 equals Response 1? &quot; + response1Body.equals(response2Body));
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>31<br>32<br>33<br>34<br>35<br>36<br>37<br>38<br>39<br>40<br>下面对以上代码进行说明：</p>
<p>我们在App的cache目录下创建了一个子目录okhttp，将其作为Okhttp专门用于缓存的目录，并设置其上限为10M，Okhttp需要能够读写该目录。</p>
<p>不要让多个缓存实例同时访问同一个缓存目录，因为多个缓存实例会相互影响，导致出错，甚至系统崩溃。在绝大多数的App中，我们只应该执行一次new OkHttpClient()，将其作为全局的实例进行保存，从而在App的各处都只使用这一个实例对象，这样所有的HTTP请求都可以共用Response缓存。</p>
<p>上面代码，我们对于同一个URL，我们先后发送了两个HTTP请求。第一次请求完成后，Okhttp将请求到的结果写入到了缓存目录中，进行了缓存。response1.networkResponse()返回了实际的数据，response1.cacheResponse()返回了null，这说明第一次HTTP请求的得到的响应是通过发送实际的网络请求，而不是来自于缓存。然后对同一个URL进行了第二次HTTP请求，response2.networkResponse()返回了null，response2.cacheResponse()返回了缓存数据，这说明第二次HTTP请求得到的响应来自于缓存，而不是网络请求。</p>
<p>如果想让某次请求禁用缓存，可以调用request.cacheControl(CacheControl.FORCE_NETWORK)方法，这样即便缓存目录有对应的缓存，也会忽略缓存，强制发送网络请求，这对于获取最新的响应结果很有用。如果想强制某次请求使用缓存的结果，可以调用request.cacheControl(CacheControl.FORCE_CACHE)，这样不会发送实际的网络请求，而是读取缓存，即便缓存数据过期了，也会强制使用该缓存作为响应数据，如果缓存不存在，那么就返回504 Unsatisfiable Request错误。也可以向请求中中加入类似于Cache-Control: max-stale=3600之类的请求头，Okhttp也会使用该配置对缓存进行处理。</p>
<p>取消请求<br>当请求不再需要的时候，我们应该中止请求，比如退出当前的Activity了，那么在Activity中发出的请求应该被中止。可以通过调用Call的cancel方法立即中止请求，如果线程正在写入Request或读取Response，那么会抛出IOException异常。同步请求和异步请求都可以被取消。</p>
<p>示例代码如下所示：</p>
<p>  private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);<br>  private final OkHttpClient client = new OkHttpClient();</p>
<p>  public void run() throws Exception {<br>    Request request = new Request.Builder()<br>        .url(“<a href="http://httpbin.org/delay/2&quot;" target="_blank" rel="noopener">http://httpbin.org/delay/2&quot;</a>) // This URL is served with a 2 second delay.<br>        .build();</p>
<pre><code>final long startNanos = System.nanoTime();
final Call call = client.newCall(request);

// Schedule a job to cancel the call in 1 second.
executor.schedule(new Runnable() {
  @Override public void run() {
    System.out.printf(&quot;%.2f Canceling call.%n&quot;, (System.nanoTime() - startNanos) / 1e9f);
    call.cancel();
    System.out.printf(&quot;%.2f Canceled call.%n&quot;, (System.nanoTime() - startNanos) / 1e9f);
  }
}, 1, TimeUnit.SECONDS);

try {
  System.out.printf(&quot;%.2f Executing call.%n&quot;, (System.nanoTime() - startNanos) / 1e9f);
  Response response = call.execute();
  System.out.printf(&quot;%.2f Call was expected to fail, but completed: %s%n&quot;,
      (System.nanoTime() - startNanos) / 1e9f, response);
} catch (IOException e) {
  System.out.printf(&quot;%.2f Call failed as expected: %s%n&quot;,
      (System.nanoTime() - startNanos) / 1e9f, e);
}
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>上述请求，服务器端会有两秒的延时，在客户端发出请求1秒之后，请求还未完成，这时候通过cancel方法中止了Call，请求中断，并触发IOException异常。</p>
<p>设置超时<br>一次HTTP请求实际上可以分为三步：</p>
<p>客户端与服务器建立连接<br>客户端发送请求数据到服务器，即数据上传<br>服务器将响应数据发送给客户端，即数据下载<br>由于网络、服务器等各种原因，这三步中的每一步都有可能耗费很长时间，导致整个HTTP请求花费很长时间或不能完成。</p>
<p>为此，可以通过OkHttpClient.Builder的connectTimeout()方法设置客户端和服务器建立连接的超时时间，通过writeTimeout()方法设置客户端上传数据到服务器的超时时间，通过readTimeout()方法设置客户端从服务器下载响应数据的超时时间。</p>
<p>在2.5.0版本之前，Okhttp默认不设置任何的超时时间，从2.5.0版本开始，Okhttp将连接超时、写入超时（上传数据）、读取超时（下载数据）的超时时间都默认设置为10秒。如果HTTP请求需要更长时间，那么需要我们手动设置超时时间。</p>
<p>示例代码如下所示：</p>
<p>  private final OkHttpClient client;</p>
<p>  public ConfigureTimeouts() throws Exception {<br>    client = new OkHttpClient.Builder()<br>        .connectTimeout(10, TimeUnit.SECONDS)<br>        .writeTimeout(10, TimeUnit.SECONDS)<br>        .readTimeout(30, TimeUnit.SECONDS)<br>        .build();<br>  }</p>
<p>  public void run() throws Exception {<br>    Request request = new Request.Builder()<br>        .url(“<a href="http://httpbin.org/delay/2&quot;" target="_blank" rel="noopener">http://httpbin.org/delay/2&quot;</a>) // This URL is served with a 2 second delay.<br>        .build();</p>
<pre><code>Response response = client.newCall(request).execute();
System.out.println(&quot;Response completed: &quot; + response);
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>如果HTTP请求的某一部分超时了，那么就会触发异常。</p>
<p>处理身份验证<br>有些网络请求是需要用户名密码登录的，如果没提供登录需要的信息，那么会得到401 Not Authorized未授权的错误，这时候Okhttp会自动查找是否配置了Authenticator，如果配置过Authenticator，会用Authenticator中包含的登录相关的信息构建一个新的Request，尝试再次发送HTTP请求。</p>
<p>示例代码如下所示：</p>
<p>  private final OkHttpClient client;</p>
<p>  public Authenticate() {<br>    client = new OkHttpClient.Builder()<br>        .authenticator(new Authenticator() {<br>          @Override public Request authenticate(Route route, Response response) throws IOException {<br>            System.out.println(“Authenticating for response: “ + response);<br>            System.out.println(“Challenges: “ + response.challenges());<br>            String credential = Credentials.basic(“jesse”, “password1”);<br>            return response.request().newBuilder()<br>                .header(“Authorization”, credential)<br>                .build();<br>          }<br>        })<br>        .build();<br>  }</p>
<p>  public void run() throws Exception {<br>    Request request = new Request.Builder()<br>        .url(“<a href="http://publicobject.com/secrets/hellosecret.txt&quot;" target="_blank" rel="noopener">http://publicobject.com/secrets/hellosecret.txt&quot;</a>)<br>        .build();</p>
<pre><code>Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response);

System.out.println(response.body().string());
</code></pre><p>  }<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>上面对以上代码进行说明：</p>
<p>OkHttpClient.Builder的authenticator()方法接收一个Authenticator对象，我们需要实现Authenticator对象的authenticate()方法，该方法需要返回一个新的Request对象，该新的Request对象基于原始的Request对象进行拷贝，而且要通过header(“Authorization”, credential)方法对其设置登录授权相关的请求头信息。</p>
<p>通过Response对象的challenges()方法可以得到第一次请求失败的授权相关的信息。如果响应码是401 unauthorized，那么会返回”WWW-Authenticate”相关信息，这种情况下，要执行OkHttpClient.Builder的authenticator()方法，在Authenticator对象的authenticate()中 对新的Request对象调用header(“Authorization”, credential)方法，设置其Authorization请求头；如果Response的响应码是407 proxy unauthorized，那么会返回”Proxy-Authenticate”相关信息，表示不是最终的服务器要求客户端登录授权信息，而是客户端和服务器之间的代理服务器要求客户端登录授权信息，这时候要执行OkHttpClient.Builder的proxyAuthenticator()方法，在Authenticator对象的authenticate()中 对新的Request对象调用header(“Proxy-Authorization”, credential)方法，设置其Proxy-Authorization请求头。</p>
<p>如果用户名密码有问题，那么Okhttp会一直用这个错误的登录信息尝试登录，我们应该判断如果之前已经用该用户名密码登录失败了，就不应该再次登录，这种情况下需要让Authenticator对象的authenticate()方法返回null，这就避免了没必要的重复尝试，代码片段如下所示：</p>
<p>if (credential.equals(response.request().header(“Authorization”))) {<br>   return null;<br>}<br>1<br>2<br>3<br>ResponseBody<br>通过Response的body()方法可以得到响应体ResponseBody，响应体必须最终要被关闭，否则会导致资源泄露、App运行变慢甚至崩溃。</p>
<p>ResponseBody和Response都实现了Closeable和AutoCloseable接口，它们都有close()方法，Response的close()方法内部直接调用了ResponseBody的close()方法，无论是同步调用execute()还是异步回调onResponse()，最终都需要关闭响应体，可以通过如下方法关闭响应体：</p>
<p>Response.close()<br>Response.body().close()<br>Response.body().source().close()<br>Response.body().charStream().close()<br>Response.body().byteString().close()<br>Response.body().bytes()<br>Response.body().string()<br>对于同步调用，确保响应体被关闭的最简单的方式是使用try代码块，如下所示：</p>
<p> Call call = client.newCall(request);<br> try (Response response = call.execute()) {<br>   … // Use the response.<br> }<br>1<br>2<br>3<br>4<br>将Response response = call.execute()放入到try()的括号之中，由于Response 实现了Closeable和AutoCloseable接口，这样对于编译器来说，会隐式地插入finally代码块，编译器会在该隐式的finally代码块中执行Response的close()方法。</p>
<p>也可以在异步回调方法onResponse()中，执行类似的try代码块，try()代码块括号中的ResponseBody也实现了Closeable和AutoCloseable接口，这样编译器也会在隐式的finally代码块中自动关闭响应体，代码如下所示：</p>
<p>   Call call = client.newCall(request);<br>   call.enqueue(new Callback() {<br>     public void onResponse(Call call, Response response) throws IOException {<br>       try (ResponseBody responseBody = response.body()) {<br>         … // Use the response.<br>       }<br>     }</p>
<pre><code>public void onFailure(Call call, IOException e) {
  ... // Handle the failure.
}
</code></pre><p>   });<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>响应体中的数据有可能很大，应该只读取一次响应体的数据。调用ResponseBody的bytes()或string()方法会将整个响应体数据写入到内存中，可以通过source()、byteStream()或charStream()进行流式处理。</p>
<p>参考：<br><a href="http://square.github.io/okhttp/3.x/okhttp/" target="_blank" rel="noopener">http://square.github.io/okhttp/3.x/okhttp/</a><br><a href="https://github.com/square/okhttp/wiki/Recipes" target="_blank" rel="noopener">https://github.com/square/okhttp/wiki/Recipes</a><br><a href="https://github.com/square/okhttp/blob/master/CHANGELOG.md" target="_blank" rel="noopener">https://github.com/square/okhttp/blob/master/CHANGELOG.md</a></p>
<p>相关阅读：<br>我的Android博文整理汇总<br>Android中HttpURLConnection使用详解 </p>
<h2 id="HTTPS理论基础及其在Android中的最佳实践"><a href="#HTTPS理论基础及其在Android中的最佳实践" class="headerlink" title="HTTPS理论基础及其在Android中的最佳实践"></a>HTTPS理论基础及其在Android中的最佳实践</h2><p>作者：孙群<br>来源：CSDN<br>原文：<a href="https://blog.csdn.net/iispring/article/details/51661195" target="_blank" rel="noopener">https://blog.csdn.net/iispring/article/details/51661195</a><br>版权声明：本文为博主原创文章，转载请附上博文链接！</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/okhttp/" rel="tag"># okhttp</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/02/docker/docker-compose配置网络/" rel="next" title="Docker系列教程24-Docker Compose网络设置">
                <i class="fa fa-chevron-left"></i> Docker系列教程24-Docker Compose网络设置
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/21/db/mysql的聚簇索引和非聚簇索引/" rel="prev" title="mysql的聚簇索引与非聚簇索">
                mysql的聚簇索引与非聚簇索 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">xiezc</p>
              <p class="site-description motion-element" itemprop="description">主要一些技术文章, 有些文章是转载的</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">72</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#下载Okhttp"><span class="nav-number">1.</span> <span class="nav-text">下载Okhttp</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Request"><span class="nav-number">1.1.</span> <span class="nav-text">Request</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HTTPS理论基础及其在Android中的最佳实践"><span class="nav-number">2.</span> <span class="nav-text">HTTPS理论基础及其在Android中的最佳实践</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xiezc</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("eRAHvO0xVYwckgdXIVpfugRG-gzGzoHsz", "57lKp708hde92YeG1xX9MQj1");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
